﻿using MemberManagement.Common;
using MemberManagement.Context;
using MemberManagement.Entity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MemberManagement
{
    public partial class RechargeForm : Form
    {
        /// <summary>
        /// 会员id
        /// </summary>
        public string MemberId { get; set; }
        private Member _member { get; set; }

        private Recharge _recharge { get; set; }

        private string PrinterName = "";

        public RechargeForm()
        {
            InitializeComponent();
            this.GetPrinterName();
        }
        #region 私有函数

        private void GetComboNameList(string name = null)
        {
            using (var db = new MyContext())
            {
                var query = db.Member.Where(m => true)
                    .OrderByDescending(m => m.CreateTime)
                    .AsQueryable();
                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where(m => m.Name.Contains(name));
                }
                var result = query.Take(20).ToArray();
                this.comboName.DataSource = result;
            }
        }
        #endregion

        private void RechargeForm_Load(object sender, EventArgs e)
        {
            this.comboName.DisplayMember = "Name";
            if (!string.IsNullOrEmpty(MemberId))
            {
                var member = GetMemberDetail(MemberId);
                this.comboName.Enabled = false;
                this.comboName.DataSource = new List<Member> { member };
                this.comboName.SelectedItem = member;
            }
        }

        private Member GetMemberDetail(string memberId)
        {
            try
            {
                using (var db = new MyContext())
                {
                    var member = db.Member.FirstOrDefault(m => m.Id == memberId);
                    if (member == null) throw new Exception("当前会员不存在");
                    return member;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        private void comboName_TextUpdate(object sender, EventArgs e)
        {
            //清空combobox
            ResetForm();
            this.GetComboNameList(this.comboName.Text);
            //设置光标位置，否则光标位置始终保持在第一列，造成输入关键词的倒序排列
            this.comboName.SelectionStart = this.comboName.Text.Length;
            //保持鼠标指针原来状态，有时候鼠标指针会被下拉框覆盖，所以要进行一次设置。
            Cursor = Cursors.Default;
            //自动弹出下拉框
            this.comboName.DroppedDown = true;
        }

        private void comboName_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectMember = this.comboName.SelectedItem as Member;
            if (selectMember != null)
            {
                this.txtCardNumber.Text = selectMember.CardNumber;
                this.txtIdCard.Text = selectMember.IdCard;
                this.txtMobile.Text = selectMember.Mobile;
                this.txtBalance.Value = selectMember.Balance;
            }
        }

        private void ResetForm()
        {
            this.comboName.DataSource = new List<Member>();
            this.comboName.SelectedItem = null;
            this.txtCardNumber.Text = string.Empty;
            this.txtIdCard.Text = string.Empty;
            this.txtMobile.Text = string.Empty;
            this.txtBalance.Value = 0M;
            this.txtRecharge.Value = 0M;
            this.txtRemark.Text = string.Empty;
        }

        private void btnRecharge_Click(object sender, EventArgs e)
        {
            ((Button)sender).Enabled = false;
            if (this.UpdateMember())
            {
                MessageBox.Show("充值成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            ((Button)sender).Enabled = true;
        }

        private bool UpdateMember()
        {
            try
            {
                using (var db = new MyContext())
                {
                    Member selectMember = this.comboName.SelectedItem as Member;
                    if (selectMember == null) throw new Exception("请先选择一个会员");
                    var member = db.Member.FirstOrDefault(m => m.Id == selectMember.Id);
                    if (member == null) throw new Exception("会员信息不存在");
                    member.Balance += this.txtRecharge.Value;
                    var recharge = new Recharge()
                    {
                        MemberId = member.Id,
                        Type = Entity.Enum.RechargeType_Enum.Recharge,
                        Amount = this.txtRecharge.Value,
                        Balance = member.Balance,
                        Remark = this.txtRemark.Text
                    };
                    db.Recharge.Add(recharge);
                    this._member = member;
                    this._recharge = recharge;
                    db.Update(member);
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }


        private void likSelectPrint_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (this._member == null || this._recharge == null)
            {
                MessageBox.Show("请先充值", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            this.printDialog1.PrinterSettings.PrinterName = this.PrinterName;
            if (this.printDialog1.ShowDialog() == DialogResult.OK)
            {
                this.SetPrinterName(this.printDialog1.PrinterSettings.PrinterName);
            }
        }

        private void SetPrinterName(string value)
        {
            var config = Application.StartupPath + @"\config.json";
            Dictionary<string, object> dic = (Dictionary<string, object>)JsonConvert.DeserializeObject<Dictionary<string, object>>(File.ReadAllText(config));
            dic["printerName"] = value;
            var json = JsonConvert.SerializeObject(dic);
            File.WriteAllText(config, json);
            this.PrinterName = value;
        }

        private void GetPrinterName()
        {
            var config = Application.StartupPath + @"\config.json";
            JObject dic = (JObject)JsonConvert.DeserializeObject(File.ReadAllText(config));
            this.PrinterName = (string)dic.SelectToken("printerName");
        }


        //打印内容的设置
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            //打印内容 为 自定义文本内容 
            if (this._member == null || this._recharge == null) return;
            int x = 10;
            int y = 20;
            int h = 20;

            e.Graphics.DrawString("充值回执", new Font("黑体", 12), Brushes.Black, new Point(55, y));
            y += h;
            e.Graphics.DrawString("姓    名:" + this._member.Name, new Font("宋体", 10), Brushes.Black, new Point(x, y));
            y += h;
            e.Graphics.DrawString("卡    号:" + this._member.CardNumber, new Font("宋体", 10), Brushes.Black, new Point(x, y));
            y += h;
            e.Graphics.DrawString("手 机 号:" + this._member.Mobile, new Font("宋体", 10), Brushes.Black, new Point(x, y));
            y += h;
            e.Graphics.DrawString("缴费时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm"), new Font("宋体", 10), Brushes.Black, new Point(x, y));
            y += h;
            e.Graphics.DrawString("缴费金额(元):" + this.txtRecharge.Value.ToString("F2"), new Font("宋体", 10), Brushes.Black, new Point(x, y));
            y += h;
            e.Graphics.DrawString("账户余额(元):" + this._member.Balance.ToString("F2"), new Font("宋体", 10), Brushes.Black, new Point(x, y));
            y += h;
            e.Graphics.DrawString(Helper.GetAppSettingValue("ComponyName", "无"), new Font("宋体", 10), Brushes.Black, new Point(x, y));
            y += h;
            e.Graphics.DrawString(Helper.GetAppSettingValue("ComponyContact", "无"), new Font("宋体", 10), Brushes.Black, new Point(x, y));
            
        }

        private void linPrint_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (this._member == null || this._recharge == null)
            {
                MessageBox.Show("请先充值", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            try
            {
                pageSetupDialog1.PrinterSettings.PrinterName = this.PrinterName;
                if (pageSetupDialog1.ShowDialog() == DialogResult.OK)
                {
                    this.printDocument1.DefaultPageSettings = pageSetupDialog1.PageSettings;
                    this.printDocument1.PrinterSettings.PrinterName = this.PrinterName;
                }
                printPreviewDialog1.Document = printDocument1;
                printPreviewDialog1.UseAntiAlias = true;
                if (printPreviewDialog1.ShowDialog() == DialogResult.OK)
                {
                    this.printDocument1.PrinterSettings.PrinterName = this.PrinterName;
                    this.printDocument1.Print();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "打印失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void printDocument1_EndPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            if (e.PrintAction == System.Drawing.Printing.PrintAction.PrintToPrinter)
            {
                printPreviewDialog1.Close();
            }
        }
    }
}
